"""

    Lamptop development utilities
    Copyright (C) 2011  Colby T. Sollars

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
"""

import MySQLdb
import re

class lamptopDatabase:
    conn = None # MySql connection object
    cursor = None # MySqle cursor
    app = None #Application object
    def __init__(self, app):
        self.app = app
    
    def connect(self, db_user, db_pass=None):
        try:
            if db_pass:
                self.conn = MySQLdb.connect(user=db_user, passwd=db_pass, db="mysql")
            else:
                self.conn = MySQLdb.connect(user=db_user, db="mysql")
        except:
            return False
        self.cursor = self.conn.cursor()
        return True
    
    def close(self):
        self.conn.close()
    
    def validate_new_db_name(self, db_name):
        error_list = []
        
        self.cursor.execute("SHOW DATABASES")
        result = self.cursor.fetchall()
        for row in result:
            if db_name == row[0]:
                error_list.append("The name '%s' is already taken. Please select another" % db_name)
        
        # if the name contains any non-alphanumeric or underscore...
        if re.search("\W", db_name):
            error_list.append("The name you entered contains disallowed characters. " + \
            "Please use only alphanumeric characters")
        return error_list
    
    def validate_new_db_username(self, username):
        error_list = []
        
        # if the name contains any non-alphanumeric or underscore...
        if re.search("\W", username):
            error_list.append("The name you entered contains disallowed characters. " + \
            "Please use only alphanumeric characters")
        
        if len(username) > 16:
            error_list.append("Username too long. Maximum length of 16 characters")
        return error_list
    
    def db_exists(self, db_name):
        self.cursor.execute("SHOW DATABASES")
        result = self.cursor.fetchall()
        for row in result:
            if db_name == row[0]:
                return True
        return False
    
    def create_database(self, db_name, db_user, db_pass):
        errors = []
        errors.extend(self.validate_new_db_name(db_name))
        errors.extend(self.validate_new_db_username(db_user))
        if len(errors):
            return errors
        
        self.cursor.execute("CREATE DATABASE %s" % db_name)
        self.cursor.execute("GRANT ALL PRIVILEGES ON %s.* to '%s'@'localhost' IDENTIFIED BY '%s'" % \
            (db_name, db_user, db_pass))
        
        return errors
    
    def drop_database(self, db_name):
        errors = []
        if not self.db_exists(db_name):
            errors.append("Database '%s' does not exist" % db_name)
        if len(errors):
            return errors
        
        self.cursor.execute("DROP DATABASE %s" % db_name)
        return errors
    
    def clear_database(self, db_name):
        errors = []
        if not self.db_exists(db_name):
            errors.append("Database '%s' does not exist" % db_name)
        if len(errors):
            return errors
        
        self.cursor.execute("USE %s" % db_name)
        self.cursor.execute("SHOW TABLES")
        result = self.cursor.fetchall()
        for row in result:
            print "Dropping table: %s" % row[0]
            self.cursor.execute("DROP TABLE %s" % row[0])
        return errors
